#include <iostream>
#include <string>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include "Socket.hpp"
#include "Protolcol.hpp"

void Usage(std::string proc)
{
    std::cout << "Usage# " << proc << "[ip]+[port] " << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(serverip, serverport);
    if (!r)
        return 1;

    srand(time(nullptr) ^ getpid());
    int cnt = 0;
    std::string opers = "+-*/%";
    std::string inbuffer_stream;
    while (cnt < 10)
    {
        std::cout<<"这是第"<<cnt<<"次测试"<<std::endl;
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100;
        usleep(3456);
        char op = opers[rand() % opers.size()];
        // 发起请求+序列化+编码
        Request req(x, y, op);
        req.DebugPrint();
        std::string package;
        req.Serialization(&package);
        package = Encode(package);

        int n = write(sockfd.Fd(), package.c_str(), package.size());
        if (n < 0)
        {
            std::cerr << "write error..." << std::endl;
            continue;
        }

        // read
        char buffer[128];
        int s = read(sockfd.Fd(), buffer, sizeof(buffer)); // 读一个完整的报文
        if (s > 0)
        {
            buffer[s] = 0;
            inbuffer_stream += buffer; //"len"\n<<"result code"\n
            // std::cout<<"inbuffer_stream"<<inbuffer_stream<<std::endl;
            // 解码
            std::string content;
            bool r = Decode(inbuffer_stream, &content); //"result""code"
            // assert(r);
            Response res;
            r = res.Deserialization(content);
            // assert(r);
            res.DebugPrint();
        }
        std::cout << "#################################" << std::endl;
        sleep(1);
        cnt++;
    }
    sockfd.Closefd();
    return 0;
}
